<template>
  <div class="leave-stats">
    <div class="header">
      <h2>请假统计</h2>
      <div class="time-range">
        <el-date-picker
          v-model="timeRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="YYYY-MM-DD"
          @change="handleTimeRangeChange"
        />
        <el-button type="primary" @click="refreshAllStats">
          <el-icon><Refresh /></el-icon>
          刷新
        </el-button>
      </div>
    </div>

    <!-- 统计概览 -->
    <div class="overview-cards">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-card class="stats-card">
            <div class="card-content">
              <div class="card-icon total-duration">
                <el-icon><Clock /></el-icon>
              </div>
              <div class="card-info">
                <div class="card-value">{{ overviewData.totalDuration || 0 }} 天</div>
                <div class="card-label">总请假时长</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stats-card">
            <div class="card-content">
              <div class="card-icon avg-duration">
                <el-icon><TrendCharts /></el-icon>
              </div>
              <div class="card-info">
                <div class="card-value">{{ overviewData.avgDuration || 0 }} 天</div>
                <div class="card-label">平均请假时长</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stats-card">
            <div class="card-content">
              <div class="card-icon total-count">
                <el-icon><Document /></el-icon>
              </div>
              <div class="card-info">
                <div class="card-value">{{ getTotalLeaveCount() }}</div>
                <div class="card-label">总请假次数</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stats-card">
            <div class="card-content">
              <div class="card-icon employee-count">
                <el-icon><User /></el-icon>
              </div>
              <div class="card-info">
                <div class="card-value">{{ getTotalEmployees() }}</div>
                <div class="card-label">涉及员工数</div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 图表区域 -->
    <div class="charts-container">
      <el-row :gutter="20">
        <!-- 部门请假统计 -->
        <el-col :span="12">
          <el-card class="chart-card">
            <template #header>
              <div class="chart-header">
                <span>部门请假统计</span>
                <el-button type="primary" text @click="loadDeptStats">刷新</el-button>
              </div>
            </template>
            <div v-loading="loading.dept" class="chart-content">
              <div v-if="deptStats.length === 0" class="empty-data">暂无数据</div>
              <div v-else ref="deptChartRef" style="height: 400px;"></div>
            </div>
          </el-card>
        </el-col>

        <!-- 月度请假趋势 -->
        <el-col :span="12">
          <el-card class="chart-card">
            <template #header>
              <div class="chart-header">
                <span>月度请假趋势</span>
                <el-select v-model="selectedYear" @change="loadMonthlyTrend" style="width: 120px;">
                  <el-option
                    v-for="year in yearOptions"
                    :key="year"
                    :label="`${year}年`"
                    :value="year"
                  />
                </el-select>
              </div>
            </template>
            <div v-loading="loading.monthly" class="chart-content">
              <div v-if="monthlyStats.length === 0" class="empty-data">暂无数据</div>
              <div v-else ref="monthlyChartRef" style="height: 400px;"></div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 个人请假排行 -->
    <el-card class="personal-stats-card" style="margin-top: 20px;">
      <template #header>
        <div class="chart-header">
          <span>个人请假排行</span>
          <el-button type="primary" text @click="loadPersonalStats">刷新</el-button>
        </div>
      </template>
      <div v-loading="loading.personal" class="personal-content">
        <el-table :data="personalStats" border stripe>
          <el-table-column type="index" label="排名" width="60" align="center" />
          <el-table-column prop="employeeName" label="员工姓名" min-width="120" />
          <el-table-column prop="personalLeaveCount" label="请假次数" width="100" align="center" />
          <el-table-column prop="personalTotalDuration" label="总时长(天)" width="120" align="center">
            <template #default="{ row }">
              {{ row.personalTotalDuration || 0 }}
            </template>
          </el-table-column>
          <el-table-column label="平均时长(天)" width="120" align="center">
            <template #default="{ row }">
              {{ row.personalLeaveCount ? (row.personalTotalDuration / row.personalLeaveCount).toFixed(1) : 0 }}
            </template>
          </el-table-column>
        </el-table>
        <div v-if="personalStats.length === 0" class="empty-data">暂无数据</div>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import { Refresh, Clock, TrendCharts, Document, User } from '@element-plus/icons-vue'
import { leaveStatsApi } from '@/api/leaveStats'
import * as echarts from 'echarts'

// 响应式数据
const timeRange = ref([])
const selectedYear = ref(new Date().getFullYear().toString())
const yearOptions = ref([])

// 统计数据
const deptStats = ref([])
const monthlyStats = ref([])
const personalStats = ref([])
const overviewData = ref({})

// 加载状态
const loading = reactive({
  dept: false,
  monthly: false,
  personal: false,
  overview: false
})

// 图表引用
const deptChartRef = ref()
const monthlyChartRef = ref()

// 图表实例
let deptChart = null
let monthlyChart = null

// 生命周期
onMounted(() => {
  initYearOptions()
  initDefaultTimeRange()
  loadAllStats()
})

// 初始化年份选项
const initYearOptions = () => {
  const currentYear = new Date().getFullYear()
  for (let year = currentYear - 2; year <= currentYear; year++) {
    yearOptions.value.push(year.toString())
  }
}

// 初始化默认时间范围（最近30天）
const initDefaultTimeRange = () => {
  const end = new Date()
  const start = new Date()
  start.setDate(start.getDate() - 30)
  timeRange.value = [
    start.toISOString().split('T')[0],
    end.toISOString().split('T')[0]
  ]
}

// 时间范围变化
const handleTimeRangeChange = () => {
  loadAllStats()
}

// 刷新所有统计
const refreshAllStats = () => {
  loadAllStats()
}

// 加载所有统计数据
const loadAllStats = () => {
  loadOverview()
  loadDeptStats()
  loadMonthlyTrend()
  loadPersonalStats()
}

// 加载总览数据
const loadOverview = async () => {
  try {
    loading.overview = true
    const params = getTimeParams()
    const response = await leaveStatsApi.getLeaveOverview(params)
    if (response && response.code === 1) {
      overviewData.value = response.data
    } else {
      ElMessage.error(response?.msg || '获取总览数据失败')
    }
  } catch (error) {
    ElMessage.error('获取总览数据失败')
  } finally {
    loading.overview = false
  }
}

// 加载部门统计
const loadDeptStats = async () => {
  try {
    loading.dept = true
    const params = getTimeParams()
    const response = await leaveStatsApi.getDeptLeaveStats(params)
    if (response && response.code === 1) {
      deptStats.value = response.data || []
      nextTick(() => {
        renderDeptChart()
      })
    } else {
      ElMessage.error(response?.msg || '获取部门统计失败')
    }
  } catch (error) {
    ElMessage.error('获取部门统计失败')
  } finally {
    loading.dept = false
  }
}

// 加载月度趋势
const loadMonthlyTrend = async () => {
  try {
    loading.monthly = true
    const response = await leaveStatsApi.getMonthlyLeaveTrend({ year: selectedYear.value })
    if (response && response.code === 1) {
      monthlyStats.value = response.data || []
      nextTick(() => {
        renderMonthlyChart()
      })
    } else {
      ElMessage.error(response?.msg || '获取月度趋势失败')
    }
  } catch (error) {
    ElMessage.error('获取月度趋势失败')
  } finally {
    loading.monthly = false
  }
}

// 加载个人统计
const loadPersonalStats = async () => {
  try {
    loading.personal = true
    const params = getTimeParams()
    const response = await leaveStatsApi.getPersonalLeaveStats(params)
    if (response && response.code === 1) {
      personalStats.value = response.data || []
    } else {
      ElMessage.error(response?.msg || '获取个人统计失败')
    }
  } catch (error) {
    ElMessage.error('获取个人统计失败')
  } finally {
    loading.personal = false
  }
}

// 获取时间参数
const getTimeParams = () => {
  if (timeRange.value && timeRange.value.length === 2) {
    return {
      startDate: timeRange.value[0],
      endDate: timeRange.value[1]
    }
  }
  return {}
}

// 渲染部门统计图表
const renderDeptChart = () => {
  if (!deptChartRef.value || deptStats.value.length === 0) return
  
  if (deptChart) {
    deptChart.dispose()
  }
  
  deptChart = echarts.init(deptChartRef.value)
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    legend: {
      data: ['请假时长', '请假次数'],
      right: 10,
      top: 5,
      orient: 'horizontal'
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      top: '15%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: deptStats.value.map(item => item.deptName),
      axisLabel: {
        rotate: 45
      }
    },
    yAxis: [
      {
        type: 'value',
        name: '时长(天)',
        position: 'left'
      },
      {
        type: 'value',
        name: '次数',
        position: 'right'
      }
    ],
    series: [
      {
        name: '请假时长',
        type: 'bar',
        yAxisIndex: 0,
        data: deptStats.value.map(item => item.totalDuration || 0),
        itemStyle: {
          color: '#5470c6'
        }
      },
      {
        name: '请假次数',
        type: 'line',
        yAxisIndex: 1,
        data: deptStats.value.map(item => item.leaveCount || 0),
        itemStyle: {
          color: '#91cc75'
        },
        lineStyle: {
          width: 3
        },
        symbol: 'circle',
        symbolSize: 8
      }
    ]
  }
  deptChart.setOption(option)
}

// 渲染月度趋势图表
const renderMonthlyChart = () => {
  if (!monthlyChartRef.value || monthlyStats.value.length === 0) return
  
  if (monthlyChart) {
    monthlyChart.dispose()
  }
  
  monthlyChart = echarts.init(monthlyChartRef.value)
  const option = {
    tooltip: {
      trigger: 'axis'
    },
    legend: {
      data: ['请假次数', '请假时长'],
      right: 10,
      top: 5,
      orient: 'horizontal'
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      top: '15%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: monthlyStats.value.map(item => item.month)
    },
    yAxis: [
      {
        type: 'value',
        name: '次数'
      },
      {
        type: 'value',
        name: '时长(天)'
      }
    ],
    series: [
      {
        name: '请假次数',
        type: 'bar',
        data: monthlyStats.value.map(item => item.monthlyLeaveCount || 0),
        itemStyle: {
          color: '#fac858'
        }
      },
      {
        name: '请假时长',
        type: 'line',
        yAxisIndex: 1,
        data: monthlyStats.value.map(item => item.monthlyDuration || 0),
        itemStyle: {
          color: '#ee6666'
        },
        lineStyle: {
          width: 3
        },
        symbol: 'circle',
        symbolSize: 8
      }
    ]
  }
  monthlyChart.setOption(option)
}

// 获取总请假次数
const getTotalLeaveCount = () => {
  if (overviewData.value.typeStats) {
    return overviewData.value.typeStats.reduce((total, item) => total + (item.typeCount || 0), 0)
  }
  return 0
}

// 获取总员工数
const getTotalEmployees = () => {
  if (overviewData.value.deptStats) {
    return overviewData.value.deptStats.reduce((total, item) => total + (item.totalEmployees || 0), 0)
  }
  return 0
}

// 组件卸载时销毁图表
const destroyCharts = () => {
  if (deptChart) {
    deptChart.dispose()
    deptChart = null
  }
  if (monthlyChart) {
    monthlyChart.dispose()
    monthlyChart = null
  }
}
</script>

<style scoped>
.leave-stats {
  padding: 20px;
  background: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #ebeef5;
}

.time-range {
  display: flex;
  align-items: center;
  gap: 10px;
}

/* 概览卡片样式 */
.overview-cards {
  margin-bottom: 20px;
}

.stats-card {
  border-radius: 8px;
  border: none;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.card-content {
  display: flex;
  align-items: center;
  padding: 10px;
}

.card-icon {
  width: 60px;
  height: 60px;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 15px;
  font-size: 24px;
  color: #fff;
}

.total-duration {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.avg-duration {
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
}

.total-count {
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
}

.employee-count {
  background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
}

.card-value {
  font-size: 24px;
  font-weight: bold;
  color: #303133;
  margin-bottom: 5px;
}

.card-label {
  font-size: 14px;
  color: #909399;
}

/* 图表卡片样式 */
.chart-card {
  margin-bottom: 20px;
  border-radius: 8px;
  border: none;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.chart-content {
  padding: 10px 0;
}

.personal-stats-card {
  border-radius: 8px;
  border: none;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.personal-content {
  padding: 10px 0;
}

.empty-data {
  text-align: center;
  color: #909399;
  padding: 50px 0;
  font-size: 14px;
}

:deep(.el-card__header) {
  padding: 15px 20px;
  border-bottom: 1px solid #ebeef5;
}

:deep(.el-table) {
  border-radius: 4px;
}
</style>